package com.lottery.ruok.lottrey.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.EmojiconsAdapter;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class EmojiconsFragment extends BaseFragment {
    @BindView(R.id.listview)
    GridView listView;

    ArrayList<Integer> datas = new ArrayList();
    private EditText myMessageEditText;

    public void setEditText(EditText myMessageEditText) {
        this.myMessageEditText = myMessageEditText;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_all_emoji, null);

        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init(){
        int[] emojis = getResources().getIntArray(com.android.lib.R.array.emoji_list);
        for (int emoji : emojis) {
            datas.add(emoji);
        }
        datas.add(-1);
        listView.setAdapter(new EmojiconsAdapter(this, datas));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(i == datas.size() - 1){
                    if(myMessageEditText.getText().toString().length() > 0) {
//                        myMessageEditText.getText().delete(myMessageEditText.getText().length() - 1, myMessageEditText.getText().length());

                        int  keyCode = KeyEvent.KEYCODE_DEL;  //这里是退格键
                        KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);

                        KeyEvent keyEventUp = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
                        myMessageEditText.onKeyDown(keyCode, keyEventDown);
                        myMessageEditText.onKeyUp(keyCode, keyEventUp);
                    }
                } else {
                    myMessageEditText.setText(myMessageEditText.getText().toString() + getEmojiStringByUnicode(datas.get(i)));
                    myMessageEditText.setSelection(myMessageEditText.getText().length());
                }
            }
        });
    }

    public String getEmojiStringByUnicode(int unicode){
        return new String(Character.toChars(unicode));
    }
}
